package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.IAction;
import com.liuqianfei.util.StringUtil;

/**
 * Proceess '\n'
 * @author liuqianfei
 */
public class NewlineAction implements IAction
{
    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        int pmax, max, pos = state.getPos();

        if (state.getSrc().charAt(pos) != 0x0A/* \n */)
            return false;

        pmax = state.getPending().length() - 1;
        max = state.getPosMax();

        // '  \n' -> hardbreak
        // Lookup in pending chars is bad practice! Don't copy to other rules!
        // Pending string is stored in concat mode, indexed lookups will cause
        // convertion to flat mode.
        if (!silent)
        {
            if (pmax >= 0 && state.getPending().charAt(pmax) == 0x20)
            {
                if (pmax >= 1 && state.getPending().charAt(pmax - 1) == 0x20)
                {
                    state.setPending(state.getPending().replaceAll("\\s+$", ""));
                    state.push("hardbreak", "br", 0);
                }
                else
                {
                    String temp = state.getPending();
                    state.setPending(StringUtil.slice(temp, 0, -1));
                    state.push("softbreak", "br", 0);
                }

            }
            else
            {
                state.push("softbreak", "br", 0);
            }
        }

        pos++;

        // skip heading spaces for next line
        while (pos < max && state.getSrc().charAt(pos) == 0x20)
            pos++;

        state.setPos(pos);
        return true;
    }
}
